package cli.menu;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.SortedSet;

import shared.Record;
import cli.CLI;
import cli.tools.Access;
import cli.tools.Tools;

//@author A0085686L
/*by LI YIN
*/
public class SearchByItemName extends Function{
	
	private static final String[] reqInput = {
		"-= Main menu > Search > Search in Receipt > Search by Item Name =-",
		"",
		"Enter the name you would like to search: "
	};
	
	private static final String[] selectItem = {
		"Select an item to view in detail by keying in its index"
	};
	
	private static final State back = State.SEARCHRECEIPTSELECTFILTER;
	private static final State current = State.SEARCHBYITEMNAME;
	
	
	public static State runMenu(){
		cli.print(reqInput);
		State nextState = current;
		
		
		String input = cli.nextLine();

		
		List<Record> searchResults = null;
		SortedSet<Record> results = null;
		try{
			results = cli.getApi().getItemNameRange(input);//Jan take note
		}
		catch(Exception e){
			cli.print(noResults);
			return current;
		}
		

		if ((results == null)|| results.isEmpty()){
			cli.print(noResults);
			return current;
		}
	
		cli.print(selectItem);
		
		// converts sortedset to an arry to a list
		Record[] temp = results.toArray(new Record[1]);
		searchResults = new ArrayList<Record>();
		for (int i = 0; i < temp.length; i++)
			searchResults.add(temp[i]);
		
		
		Object choice = tools.selectFromList(searchResults, "searchByItemName");
		
		// if user selected back
		if (choice == null) {
			// go back to searchSelectFilter
			return back;
		}

		// if user's choice diverts to another menu (e.g, home)
		if (choice.getClass() == State.class) {
			return (State) choice;
		}

		// if user selected a good choice
		Record toView = (Record) choice;
		Access.viewRecord(toView);
		Access.modifyRecord(toView);
		
		return nextState;
		

	}
}
